package com.wwwarehouse.taskcenter.fragment.job_point.step1;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.ParentJobPointResponseBean;
import com.wwwarehouse.taskcenter.bean.job_point.WarehouseResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.constant.job_point.JobSaveConstant;
import com.wwwarehouse.taskcenter.eventbus_event.TaskPointCardEvent;
import com.wwwarehouse.taskcenter.tools.UserCenterCheckUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_BUSINESS_ID;

/**
 * @创建者 chenchao.
 * @创建时间 2017/10/24 10:52
 * @描述 新增作业点第一步
 */

public class AddJobPointNameFragment extends BaseFragment implements View.OnClickListener, View.OnTouchListener {

    private View mRootView;
    private ElasticScrollView mElasticScrollView;
    private StateLayout mStateLayout;
    private RelativeLayout mRlTaskPoint;
    private RelativeLayout mRlTaskPointChild;
    private StateButton mParentJobPointNormalBtn;
    private StateButton mParentJobPointCheckBtn;
    private StateButton mChildJobPointCheckBtn;
    private StateButton mChildJobPointNormalBtn;
    private RelativeLayout mRlTaskPointChoose;
    private RelativeLayout mRlTaskPointChooseChild;
    private ClearEditText mCetPositionName;
    private EditText mEtMessage;
    private StateButton mBtSave;
    private LinearLayout mLlChoseWare;
    private LinearLayout mLlChosePosition;
    private TextView mTvChooseWare;
    private TextView mTvChoosePosition;

    private String mBusinessId;   //业务单位id
    private boolean mIsParentJobPoint = false;    //标记是否是父作业点
    private String mWarehouseUkId;    //仓库id
    private String mWarehouseName;  //仓库name

    private List<ParentJobPointResponseBean.ParentJobPointBean> mParentJobPointList;
    private List<WarehouseResponseBean.WarehouseDetailsBean> mWarehouseDetailsList;
    private WarehouseResponseBean.WarehouseDetailsBean mWarehouseDetailsBean;
    private ParentJobPointResponseBean.ParentJobPointBean mParentJobPointBean;

    private static final int REQUEST_GET_PARENT_JOB_POINT = 0;
    private static final int REQUEST_GET_WAREHOUSE_INFO = 1;
    private static final int REQUEST_SAVE_JOB_POINT_NAME = 2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_add_job_point_name, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mElasticScrollView = findView(mRootView, R.id.esv_elastic);
        mStateLayout = findView(mRootView, R.id.sl_layout);
        mStateLayout.showProgressView(true);
        mRlTaskPoint = findView(mRootView, R.id.rl_task_point); //创建父作业点时显示
        mRlTaskPointChild = findView(mRootView, R.id.rl_task_point_child);//创建子作业点时显示
        mParentJobPointNormalBtn = findView(mRootView, R.id.btn_parent_job_point_normal);
        mParentJobPointCheckBtn = findView(mRootView, R.id.btn_parent_job_point_check);
        mChildJobPointCheckBtn = findView(mRootView, R.id.btn_child_job_point_check);
        mChildJobPointNormalBtn = findView(mRootView, R.id.btn_child_job_point_normal);
        mRlTaskPointChoose = findView(mRootView, R.id.rl_task_point_choose); //创建父作业点时的选择
        mRlTaskPointChooseChild = findView(mRootView, R.id.rl_task_point_choose_child);  //创建子作业点时的选择
        mLlChoseWare = findView(mRootView, R.id.ll_chose_ware); //父作业点时 选择仓库
        mTvChooseWare = findView(mRootView, R.id.tv_choose_ware);//父作业点时 显示选择仓库
        mLlChosePosition = findView(mRootView, R.id.ll_chose_position);//子作业点 选择挂靠作业点
        mTvChoosePosition = findView(mRootView, R.id.tv_choose_position);//子作业点 显示选择挂靠作业点
        mCetPositionName = findView(mRootView, R.id.cet_position_name); //输入作业点
        mCetPositionName.setFilters(new InputFilter[]{UserCenterCheckUtils.limitLength(20)});
        mEtMessage = findView(mRootView, R.id.et_message); //附加信息
        mBtSave = findView(mRootView, R.id.bt_save);
        ((BaseCardDeskActivity) mActivity).setTitleBt1Text("修改");
        ((BaseCardDeskActivity) mActivity).setTitleBt2Text("查看");
        ((BaseCardDeskActivity) mActivity).setTitleBt1Enable(true);
        ((BaseCardDeskActivity) mActivity).setTitleBt2Enable(true);
    }

    private void initData() {
        Bundle bundle = getArguments();

        if (bundle != null) {
            mBusinessId = bundle.getString(KEY_BUSINESS_ID);
        }
    }

    private void initEvent() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                ((BaseCardDeskActivity) mActivity).showTitleBt2();
                ((BaseCardDeskActivity) mActivity).downPull_3();
            }

            @Override
            public void onUpPull() {

            }
        });

        mCetPositionName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkSaveBtn();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mParentJobPointNormalBtn.setOnClickListener(this);
        mParentJobPointCheckBtn.setOnClickListener(this);
        mChildJobPointCheckBtn.setOnClickListener(this);
        mChildJobPointNormalBtn.setOnClickListener(this);

        mLlChoseWare.setOnClickListener(this);
        mLlChosePosition.setOnClickListener(this);

        mEtMessage.setOnTouchListener(this);

        mBtSave.setOnClickListener(this);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof AddJobPointNameFragment) {
            mActivity.setTitle(getString(R.string.new_task_newpoint_name));
        }
    }

    @Override
    public void requestDatas() {
        getParentJobPoint();
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText而且当前EditText能够滚动，则将事件交给EditText处理。否则将事件交由其父类处理
        if ((view.getId() == R.id.et_message && canVerticalScroll(mEtMessage))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }

    /**
     * EditText竖直方向能否够滚动
     * @param editText  须要推断的EditText
     * @return  true：  能够滚动   false：不能够滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_parent_job_point_normal) {
            // 选中父作业点
            mParentJobPointNormalBtn.setVisibility(View.INVISIBLE);
            mParentJobPointCheckBtn.setVisibility(View.VISIBLE);

            mChildJobPointCheckBtn.setVisibility(View.INVISIBLE);
            mChildJobPointNormalBtn.setVisibility(View.VISIBLE);

            mRlTaskPointChoose.setVisibility(View.VISIBLE);
            mRlTaskPointChooseChild.setVisibility(View.GONE);

            checkSaveBtn();

            // 点击保存按钮，保存的是父作业点
            mIsParentJobPoint = true;
        } else if (id == R.id.btn_child_job_point_normal) {
            mParentJobPointNormalBtn.setVisibility(View.VISIBLE);
            mParentJobPointCheckBtn.setVisibility(View.INVISIBLE);

            mChildJobPointCheckBtn.setVisibility(View.VISIBLE);
            mChildJobPointNormalBtn.setVisibility(View.INVISIBLE);

            mRlTaskPointChoose.setVisibility(View.GONE);
            mRlTaskPointChooseChild.setVisibility(View.VISIBLE);

            checkSaveBtn();

            // 点击保存按钮，保存的是子作业点
            mIsParentJobPoint = false;
        } if (id == R.id.ll_chose_ware) {       //父作业点时 选择仓库
            chooseWarehouse();
        } else if(id==R.id.ll_chose_position){  //子作业点 选择挂靠作业点
            choosePosition();
        } else if (id == R.id.bt_save) {
            saveJobPointName();
        }
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {

        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_PARENT_JOB_POINT:
                    if ("0".equals(commonClass.getCode())) {
                        ParentJobPointResponseBean parentJobPointResponseBean = JSON.parseObject(commonClass.getData().toString(), ParentJobPointResponseBean.class);
                        mParentJobPointList = parentJobPointResponseBean.getList();

                        if (mParentJobPointList != null && mParentJobPointList.size() > 0) {
                            // 有父作业点，创建子作业点
                            mRlTaskPoint.setVisibility(View.GONE);
                            mRlTaskPointChoose.setVisibility(View.GONE);
                            mRlTaskPointChild.setVisibility(View.VISIBLE);
                            mRlTaskPointChooseChild.setVisibility(View.VISIBLE);

                            mIsParentJobPoint = false;
                        } else {
                            // 没有父作业点，创建父作业点
                            mRlTaskPoint.setVisibility(View.VISIBLE);
                            mRlTaskPointChoose.setVisibility(View.VISIBLE);
                            mRlTaskPointChild.setVisibility(View.GONE);
                            mRlTaskPointChooseChild.setVisibility(View.GONE);

                            mIsParentJobPoint = true;
                        }
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), true);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(true);

                                getParentJobPoint();
                            }
                        });
                    }
                    break;
                case REQUEST_GET_WAREHOUSE_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        WarehouseResponseBean warehouseResponseBean  = JSON.parseObject(commonClass.getData().toString(), WarehouseResponseBean.class);
                        mWarehouseDetailsList = warehouseResponseBean.getList();

                        List<String> nameList = new ArrayList<>();

                        for (WarehouseResponseBean.WarehouseDetailsBean warehouseDetailsBean : mWarehouseDetailsList) {
                            nameList.add(warehouseDetailsBean.getName());
                        }

                        if (nameList.size() > 0) {
                            showJobPointDialog(nameList, getString(R.string.choose_warehouse), "P");
                        }
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                case REQUEST_SAVE_JOB_POINT_NAME:
                    if ("0".equals(commonClass.getCode())) {
                        TaskPointCardEvent taskPointCardEvent = new TaskPointCardEvent();
                        taskPointCardEvent.setFinish1(true);

                        JobSaveConstant.Step1 step1 = new JobSaveConstant.Step1();
                        step1.setJobPointUkid(commonClass.getData().toString());
                        step1.setParentJobPoint(mIsParentJobPoint);
                        step1.setWarehouseUkid(mWarehouseUkId);
                        step1.setWarehouseName(mWarehouseName);

                        taskPointCardEvent.setObject(step1);
                        EventBus.getDefault().post(taskPointCardEvent);

                        popFragment();
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(true);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(true);

                    getParentJobPoint();
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
            dismissProgressDialog();
        }
    };

    /**
     * 查询业务单位下的父作业点
     */
    private void getParentJobPoint() {
        Map map = new HashMap();

        map.put("buId", mBusinessId);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_GET_PARENT_JOB_POINT, map, mOnResponseListener, REQUEST_GET_PARENT_JOB_POINT);
    }

    /**
     * 查询仓库信息
     */
    private void chooseWarehouse() {
        showProgressDialog();

        Map map = new HashMap();

        map.put("ownerUkid", mBusinessId);
        Map queryMap = new HashMap();
        queryMap.put("size", -1);
        map.put("query", queryMap);
        map.put("type", "H_STOCK");

        NoHttpUtils.httpPost(TaskCenterConstant.URL_GET_WAREHOUSE_INFO, map, mOnResponseListener, REQUEST_GET_WAREHOUSE_INFO);
    }

    /**
     * 选择挂靠点
     */
    private void choosePosition() {
        List<String> nameList = new ArrayList<>();

        for (ParentJobPointResponseBean.ParentJobPointBean parentJobPointBean : mParentJobPointList) {
            nameList.add(parentJobPointBean.getJobPointName());
        }

        if (nameList.size() > 0) {
            showJobPointDialog(nameList, getString(R.string.choose_position), "C");
        }
    }

    /**
     * 保存作业点名字
     */
    private void saveJobPointName() {
        showProgressDialog(getString(R.string.saving));

        Map map = new HashMap();

        map.put("addDesc", mEtMessage.getText().toString().trim());
        map.put("buId", mBusinessId);
        map.put("name", mCetPositionName.getText().toString().trim());

        if (mIsParentJobPoint) {
            //保存父作业点
            map.put("stockUkid", mWarehouseDetailsBean.getAbstractObjectUkid());
            map.put("type", "P");
        } else {
            //保存子作业点
            map.put("stockUkid", mParentJobPointBean.getStockUkid());
            map.put("parentPointUkid", mParentJobPointBean.getJobPointUkid());
            map.put("type", "C");
        }

        NoHttpUtils.httpPost(TaskCenterConstant.URL_SAVE_JOB_POINT_NAME, map, mOnResponseListener, REQUEST_SAVE_JOB_POINT_NAME);
    }

    private void showJobPointDialog(List<String> list, String title, final String type) {
        new ChoosePickerDialog.Builder(mActivity).setData(list).setTitle(title).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
            @Override
            public void onSelected(String itemValue, int position) {
                if ("P".equals(type)) {
                    mWarehouseDetailsBean = mWarehouseDetailsList.get(position);
                    mTvChooseWare.setText(itemValue);

                    mWarehouseUkId = mWarehouseDetailsBean.getAbstractObjectUkid();
                    mWarehouseName = mWarehouseDetailsBean.getName();
                } else if ("C".equals(type)) {
                    mParentJobPointBean = mParentJobPointList.get(position);
                    mTvChoosePosition.setText(itemValue);

                    mWarehouseUkId = mParentJobPointBean.getStockUkid();
                    mWarehouseName = mParentJobPointBean.getStockName();
                }

                checkSaveBtn();
            }

            @Override
            public void onCancel() {

            }
        }).create().show();
    }

    private void checkSaveBtn() {
        if (!TextUtils.isEmpty(mCetPositionName.getText().toString())) {
            if (mRlTaskPointChoose.getVisibility() == View.VISIBLE && mRlTaskPointChooseChild.getVisibility() == View.GONE) {
                if (!TextUtils.equals("请选择", mTvChooseWare.getText().toString())) {
                    mBtSave.setEnabled(true);
                } else {
                    mBtSave.setEnabled(false);
                }
            } else if (mRlTaskPointChoose.getVisibility() == View.GONE && mRlTaskPointChooseChild.getVisibility() == View.VISIBLE) {
                if (!TextUtils.equals("请选择", mTvChoosePosition.getText().toString())) {
                    mBtSave.setEnabled(true);
                } else {
                    mBtSave.setRound(false);
                }
            }
        } else {
            mBtSave.setEnabled(false);
        }
    }
}
